from flask import jsonify
from app.extensions import db
from flask_login import UserMixin
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash


# User model
class User(db.Model, UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20))
    nickname = db.Column(db.String(20))
    password_hash = db.Column(db.String(128))
    last_ip = db.Column(db.String(16))
    last_login_at = db.Column(db.DateTime, default=datetime.utcnow)

    @property
    def password(self):
        return self.password_hash

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def validate_password(self, password):
        return check_password_hash(self.password_hash, password)

    def to_json(self):
        return jsonify({
            'id': self.id,
            'username': self.username,
            'nickname': self.nickname
        })

    @property
    def count(self):
        return 100
